#!/usr/bin/python

from numpy import sqrt,arange,linspace,meshgrid,ones

def create_GRASP_tab_surf( out_name, (xmin,xmax), (ymin,ymax), (Ny, Nx), Z_values ):
  "Creates a file named out_name.sfc using the Tabulated Surface GRASP format described\
   in the GRASP v10.2 Manual (p. 286). \
   \
   INPUT\
     outname        [string]     : name of the file containing the surface points. .sfc extension is always appended.\
     (xmin,xmax)    [ tuple]  : tuple containing x-axis limits xmin and xmax.\
     (ymin,ymax)    [ tuple]  : tuple containing y-axis limits ymin and ymax.\
     (Nx , Ny  )    [ tuple]  : tuple containing the number of points in the x-axis and y-axis, respectively.\
     Z_values [ numpy array]  : 1xN Numpy array containing Z values for the surface on the specified X-Y range.\
  \
  RETURNS\
    0 [int]                   : if everything went well :)\
   -1 [int]                   : if number of grid points is different from the number of Z values.\
  "
  if Nx * Ny != Z_values.shape[0]:
    print "FATAL ERROR : NUMBER OF GRID POINTS DIFFERS FROM NUMBER OF Z VALUES. ABORTING"
    return -1

  #Create equally separated (regular) grid points
  x   = linspace( xmin,xmax, Nx )
  y   = linspace( ymin,ymax, Ny )

  #Create file object
  out_file = open( out_name + ".sfc", 'w' )

  out_file.write("Regular grid surface file for GRASP\n")
  out_file.write('%4.10f  %4.10f  %4.10f  %4.10f\n' % (xmin,ymin,xmax,ymax) )
  out_file.write('%04d  %04d\n' % (Nx,Ny) )
  
  for z in Z_values:
    out_file.write('%4.10f\n' % (z) )

  return 0

Z_val = ones( (256) )
create_GRASP_tab_surf( 'test', (-1,1), (-1,1), (16,16), Z_val )
